package org.benjamin.tenancy.service.impl;

import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.benjamin.tenancy.domain.entity.CheckInLog;
import org.benjamin.tenancy.domain.entity.Housing;
import org.benjamin.tenancy.domain.entity.Tenant;
import org.benjamin.tenancy.repository.CheckInLogRepository;
import org.benjamin.tenancy.repository.HousingRepository;
import org.benjamin.tenancy.repository.TenantRepository;
import org.benjamin.tenancy.service.HousingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Transactional
@Service("housingService")
public class HousingServiceImpl implements HousingService {

	private Logger logger  = LogManager.getLogger();
	
	@Autowired
	private HousingRepository housingRepository;

	@Autowired
	private TenantRepository tenantRepository;

	@Autowired
	private CheckInLogRepository checkInLogRepository;

	@Override
	public List<Housing> findByHousingBuildingId(Integer buildingId) {
		return this.housingRepository.findByBuildingId(buildingId, new Sort("number"));
	}

	@Override
	public Housing findEntityById(Integer id) {
		return this.housingRepository.findOne(id);
	}


	@Override
	public void checkIn(Integer housingId,Tenant tenant) {
		if(tenant != null){
			logger.info("完成租客信息登录");
			tenant.setId(housingId);
			this.tenantRepository.save(tenant);

			CheckInLog checkInLog = new CheckInLog();
			checkInLog.setHousingId(tenant.getId());
			checkInLog.setTenantName(tenant.getUsername());
			checkInLog.setTenantPhone(tenant.getPhone());
			checkInLog.setTenantIdentity(tenant.getIdentityNumber());
			this.checkInLogRepository.save(checkInLog);
			logger.info("完成对租客信息入住记录");

		}else{
			logger.info("租客信息不存在，直接登修改租房状态");
		}
		Housing housing = this.housingRepository.findOne(housingId);
		housing.setStatus(true);
		this.housingRepository.save(housing);


	}

}
